package com.red.service.impl;

import com.red.pojo.Result;
import com.red.pojo.model.LoginUser;
import com.red.pojo.entity.User;
import com.red.service.ILoginService;
import com.red.service.IUserService;
import com.red.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private IUserService userService;

    @Override
    public Result login(String account, String password) {
        if (account.isEmpty() || password.isEmpty()) {
            return Result.error("账号或密码不能为空");
        }

        User user = userService.selectUserByAccount(account);

        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());

        if (user == null || !user.getPassword().equals(md5Password)) {
            return Result.error("账号或密码错误");
        }

        LoginUser loginUser = new LoginUser();
        loginUser.setUserID(user.getUserId());
        loginUser.setLoginTime(new Date().getTime());

        Result result = Result.success("登录成功");

        Map<String, Object> userInfoMap = new HashMap<>();
        userInfoMap.put("userName", user.getUserName());
        userInfoMap.put("headImg", user.getProfile());
        userInfoMap.put("userLevel", user.getUserLevel());

        result.put("token", JWTUtil.createJWT(loginUser));
        result.put("userInfo", userInfoMap);

        return result;
    }
}
